package com.cgnpc.scp.run.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cgnpc.cud.core.common.util.MessageUtils;
import com.cgnpc.cud.core.domain.AjaxResult;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.scp.common.bean.CreateFileInfo;
import com.cgnpc.scp.common.bean.MyPageResult;
import com.cgnpc.scp.common.exception.ScpException;
import com.cgnpc.scp.common.service.AppConstantService;
import com.cgnpc.scp.common.utils.MyPageResultUtil;
import com.cgnpc.scp.common.utils.SqlUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.config.MockClient;
import com.cgnpc.scp.run.mybatis.entity.*;
import com.cgnpc.scp.run.mybatis.mapper.client.MarketInfoMapper;
import com.cgnpc.scp.run.mybatis.mapper.client.ProjectInfoMapper;
import com.cgnpc.scp.run.pojo.MarketInfoVo;
import com.cgnpc.scp.run.service.MarketInfoService;
import com.cgnpc.scp.run.service.MarketReviewService;
import com.cgnpc.scp.run.utils.CommonExportUtil;
import com.cgnpc.scp.run.utils.HttpClientUtil;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.*;

/**********************************
 * 用途说明: 市场机会service
 * 作者姓名: zhangyibing
 * 创建时间: 2020年9月13日15:51:35
 ***********************************/
@Service("marketInfoService")
public class MarketInfoServiceImpl implements MarketInfoService {
    private static final Logger LOGGER = LoggerFactory.getLogger(MarketInfoServiceImpl.class);

    @Autowired
    private MarketInfoMapper marketInfoMapper;

    @Autowired
    private MarketReviewService marketReviewService;

    @Autowired
    private ProjectInfoMapper projectInfoMapper;

    @Autowired
    private AppConstantService appConstantService;

    @Autowired
    private SqlSession sqlSession;

    @Value("${imsme.url}")
    private String url;
    @Value("${imsme.projectdept}")
    private String projectdept;
    @Value("${imsme.systemappname}")
    private String systemappname;

    @Autowired
    private MockClient mockClient;
    @Autowired
    private RestTemplate restTemplate;

    private String devMode;

    @Value("${spring.profiles.usemock}")
    public void setDevMode(String dm) {
        devMode = dm;
    }

    @Override
    public MyPageResult<MarketInfo> queryMarketInfoPageList(MarketInfo marketInfo) {
        MyPageResult<MarketInfo> re = null;

        int pageNum = marketInfo.getPageNum();
        int pageSize = marketInfo.getPageSize();
        String searchKey = marketInfo.getMarketName();
        Page<MarketInfo> page = new Page<>(pageNum, pageSize);

        IPage<MarketInfo> pageResult = marketInfoMapper.selectPage(page,
                new QueryWrapper<MarketInfo>().like(!StringUtil.isNullOrSpace(searchKey), "market_name", searchKey)
                        .or().like(!StringUtil.isNullOrSpace(searchKey), "customer_name", searchKey)
        );
        re = MyPageResultUtil.createMyPageResultPlus(pageResult);
        return re;
    }

    /**
     * 创建查询Example
     */
//    private MarketInfoExample createQueryExample(MarketInfo reqEntity) {
//        MarketInfoExample example = new MarketInfoExample();
//        if(!StringUtil.isNullOrSpace(reqEntity.getMarketName())){
//            MarketInfoExample.Criteria criteria = example.createCriteria();
//            criteria.andMarketNameLike(SqlUtil.valueJoinLikeBoth(reqEntity.getMarketName()));
//            MarketInfoExample.Criteria customerNameCriteria = example.createCriteria();
//            customerNameCriteria.andCustomerNameLike(SqlUtil.valueJoinLikeBoth(reqEntity.getMarketName()));
//            example.or(customerNameCriteria);
//        }
//        return example;
//    }


    @Override
    public MarketInfoVo getMarketInfoById(String id) {
        MarketInfoVo result = null;

        MarketInfo marketInfo = marketInfoMapper.selectById(id);
        if(marketInfo == null){
            return result;
        }
        result = new MarketInfoVo();
        MarketReview review = marketReviewService.getReviewByInfoId(marketInfo.getId());

        List<ProjectInfo> projectInfos = projectInfoMapper.selectList(new QueryWrapper<ProjectInfo>()
        .eq("marketinfoid", id));
        ProjectInfo projectInfo = null;
        if(projectInfos != null && projectInfos.size() != 0){
            projectInfo = projectInfos.get(0);
        }
        result.setProjectInfo(projectInfo);
        result.setMarketInfo(marketInfo);
        result.setMarketReview(review);

        return result;
    }

    @Override
    public <T extends MarketInfo> CreateFileInfo exportExcel(T reqEntity) throws Exception {
        final String logInfo = "[exportExcel_UUID_" + UUID.randomUUID() + "]";
        CreateFileInfo createFileInfo = null;

        try {
            List<String> titleList = Arrays.asList(
                    "市场机会名称","项目类型","客户名称"
                    ,"信息来源","预计合同金额（万元）","信息有效期截止","密级","项目属性"
                    ,"项目区域","项目厂址","资金来源","项目承揽模式"
            );
            List<String> fields = Arrays.asList("marketName","projectType", "customerName"
                    ,"messageFunds","estimateAmount","informationValid","secretlevel","projectAttribute"
                    ,"projectArea","projectAddress","sourceFunds","projectContract"
            );

            CommonExportUtil<MarketInfo> util = new CommonExportUtil<>();
            createFileInfo = util.exportExcel(appConstantService, sqlSession, titleList, fields
                            , "com.cgnpc.scp.run.mybatis.mapper.client.MarketInfoMapper"
                            ,"selectPageExport", reqEntity);
        } catch (Exception e) {
            LOGGER.error("{}error;", logInfo, e);
            throw e;
        }

        return createFileInfo;
    }

    /**
     * 同心圆取号
     */
    @Override
    public AjaxResult offerNumber(Map<String, Object> param) {
        String marketInfoId = (String)param.get("marketInfoId");
        if(StringUtil.isNullOrSpace(marketInfoId)){
            throw new ScpException("marketInfoId can not be null");
        }
        String projectId = (String)param.get("projectId");
        if(StringUtil.isNullOrSpace(projectId)){
            throw new ScpException("projectId can not be null");
        }
        projectInfoMapper.clearOfferNumber(param);
        projectInfoMapper.offerNumber(param);
        return AjaxResult.success();
    }

    @Override
    @Scheduled(cron = "${imsme.cron}")
    public Object getMarketInfoByTimer() throws Exception {
        if("local".equals(devMode)) {
            LinkedHashMap<String,Object> invoke = mockClient.invoke("marketInfoService", "getMarketInfoByTimer", null, LinkedHashMap.class);
            LOGGER.info("invoke:{}", invoke);
            saveTimerData(invoke);
            return invoke;
        }
        String json = "{\"pageSize\":\"10000\",\"pageIndex\":\"1\",\"ProjectDept\":\""+this.projectdept+"\",\"SystemAppName\":\""+this.systemappname+"\"}";
        String url = this.url + "?requestParam="+json;
        //调用远程接口
        LOGGER.info("url:{}", url);
        String response = HttpClientUtil.insureResponseBlockGet(url);
        //System.out.println(response.getClass().getName());
        JSONObject responseJson = JSONObject.parseObject(response);
        Map<String, Object> repsonseMap = (Map<String,Object>)responseJson;
        LOGGER.info("result:{}", response);
        saveTimerData(repsonseMap);
        return response;
    }


    private void saveTimerData(Object response) throws Exception {
        Map<String, Object> invoke = (Map)response;
        if(invoke == null){
            return ;
        }
        String responseCode = invoke.get("Code")+"";
        if(!"200".equals(responseCode)){
            throw new Exception(MessageUtils.message("cud.bpmcenter.error",invoke.get("Msg")));
        }
        Map<String, Object> dataInfo = (Map) invoke.get("DataInfo");
        List<String> uids = marketInfoMapper.getUids();
//        List<String> uids = new ArrayList<>();
        Object projects = dataInfo.get("ConcentricCircleProjects");
        List<Map> data;
        if(projects instanceof JSONArray){
            data = ((JSONArray) projects).toJavaList(Map.class);
        }else{
            data = (List)dataInfo.get("ConcentricCircleProjects");
        }
        for(int i=0; i<data.size(); i++){
            Map<String, Object> obj = (Map)data.get(i);
            String uid = obj.get("Uuid")+"";
            if(uids != null && !uids.contains(uid)){
                MarketInfo info = new MarketInfo();
                info.setId(IDHelper.uuid());
                info.setUid(uid);
                //市场机会名称
                info.setMarketName(obj.get("ProjectName")==null?"":obj.get("ProjectName")+"");
                //项目类型
                info.setProjectType(obj.get("ProjectType")==null?"":obj.get("ProjectType")+"");
                //客户类型
                info.setCustomerType(obj.get("CustomType")==null?"":obj.get("CustomType")+"");
                //客户名称
                info.setCustomerName(obj.get("OwnerCompany")==null?"":obj.get("OwnerCompany")+"");
                //预计金额
                info.setEstimateAmount(obj.get("Investment")==null?"":obj.get("Investment")+"");
                //项目区域
                info.setProjectArea(obj.get("ProjectArea")==null?"":obj.get("ProjectArea")+"");
                //承揽模式
                info.setProjectContract(obj.get("UndertakeModel")==null?"":obj.get("UndertakeModel")+"");
                //项目所属部门
                info.setProjectDept(obj.get("ProjectDept")==null?"":obj.get("ProjectDept")+"");
                //客户简要介绍
                info.setProjectBackground(obj.get("ProjectBackground")==null?"":obj.get("ProjectBackground")+"");
                //项目工作范围
                info.setProjectCondition(obj.get("ProjectCondition")==null?"":obj.get("ProjectCondition")+"");
                //能力及业绩
                info.setContractorRequire(obj.get("ContractorRequire")==null?"":obj.get("ContractorRequire")+"");
                //意义及其他说明
                info.setLocalSituation(obj.get("LocalSituation")==null?"":obj.get("LocalSituation")+"");

                info.setCreateTime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(obj.get("CreateDate")+""));
                info.setCreateUser(obj.get("CreatorNo")+"");
                info.setCreateUserName(obj.get("CreatorName")+"");

                info.setLastUpdateTime(info.getCreateTime());
                marketInfoMapper.insert(info);
            }

        }
    }

    public static void main(String[] args) throws Exception{
        String json = "{\n" +
                "\t\"Code\": 200,\n" +
                "\t\"Msg\": \"获取成功\",\n" +
                "\t\"DataInfo\": {\n" +
                "\t\t\"PageSize\": 10,\n" +
                "\t\t\"ConcentricCircleProjects\": [{\n" +
                "\t\t\t\"Uuid\": \"0300db8f-cb7a-4082-b4da-05835ee5203e\",\n" +
                "\t\t\t\"ProjectType\": \"核电工程\",\n" +
                "\t\t\t\"ProjectName\": \"232323dfdfdf\",\n" +
                "\t\t\t\"ProjectAttribute\": \"\",\n" +
                "\t\t\t\"OwnerCompany\": \"23\",\n" +
                "\t\t\t\"Investment\": \"23\",\n" +
                "\t\t\t\"ProjectArea\": \"INTERNATIONAL\",\n" +
                "\t\t\t\"UndertakeModel\": \"单板块业务\",\n" +
                "\t\t\t\"ProjectDept\": \"EDE\",\n" +
                "\t\t\t\"ProjectBackground\": \"2323dfdf\",\n" +
                "\t\t\t\"ProjectCondition\": \"dfdsf\",\n" +
                "\t\t\t\"ContractorRequire\": \"sfsdfsdf\",\n" +
                "\t\t\t\"LocalSituation\": \"dfdsf\",\n" +
                "\t\t\t\"CreatorNo\": \"P121737\",\n" +
                "\t\t\t\"CreatorName\": \"郭坚涛\",\n" +
                "\t\t\t\"CreatorDept\": \"\",\n" +
                "\t\t\t\"CreateDate\": \"2020-08-10 17:22:52\",\n" +
                "\t\t\t\"AttachFileLists\": []\n" +
                "\t\t}, {\n" +
                "\t\t\t\"Uuid\": \"0d695d1e-91fb-44c3-be2e-1de29700f772\",\n" +
                "\t\t\t\"ProjectType\": \"核电工程\",\n" +
                "\t\t\t\"ProjectName\": \"22323钉钉\",\n" +
                "\t\t\t\"ProjectAttribute\": \"\",\n" +
                "\t\t\t\"OwnerCompany\": \"23\",\n" +
                "\t\t\t\"Investment\": \"3\",\n" +
                "\t\t\t\"ProjectArea\": \"INTERNATIONAL\",\n" +
                "\t\t\t\"UndertakeModel\": \"单板块业务\",\n" +
                "\t\t\t\"ProjectDept\": \"EDE\",\n" +
                "\t\t\t\"ProjectBackground\": \"33\",\n" +
                "\t\t\t\"ProjectCondition\": \"33\",\n" +
                "\t\t\t\"ContractorRequire\": \"333\",\n" +
                "\t\t\t\"LocalSituation\": \"33\",\n" +
                "\t\t\t\"CreatorNo\": \"P121737\",\n" +
                "\t\t\t\"CreatorName\": \"郭坚涛\",\n" +
                "\t\t\t\"CreatorDept\": \"\",\n" +
                "\t\t\t\"CreateDate\": \"2020-07-25 20:09:35\",\n" +
                "\t\t\t\"AttachFileLists\": []\n" +
                "\t\t}],\n" +
                "\t\t\"PageIndex\": 1,\n" +
                "\t\t\"SumCount\": 14,\n" +
                "\t\t\"SumPageCount\": 2\n" +
                "\t}\n" +
                "}";
        JSONObject responseJson = JSONObject.parseObject(json);
        Map<String, Object> repsonseMap = (Map<String,Object>)responseJson;
        new MarketInfoServiceImpl().saveTimerData(repsonseMap);
    }
}
